// pages/releaseList/releaseList.js
import {
  getFirstAddress,
  getSecondAddress,
}
from "../../apis/address_api"
import {
  deleteAdvise
}
from "../../apis/release_api"
import {
  getAdvisePage
}
from "../../apis/advise_api"
Page({
  /**
   * 页面的初始数据
   */
  data: {
    watermarkText: wx.getStorageSync("name") + wx.getStorageSync("phoneNumber").slice(-4),
     deleindex:null,
    // 删除按钮控制器
    showDelete: false,
    // 用户权限代码
    code: 0,
    // 一级权限代码
    firstCode: getApp().globalData.firstCode,
    // 二级权限代码
    secondCode: getApp().globalData.secondCode,
    // 一级辖区
    firstAddress: "",
    // 二级辖区
    secondAddress: "",
    // 一级管理员辖区列表
    locationList: [
      [],
      []
    ],
    // 二级管理员辖区列表
    addressList: [],
    // 选中导航栏的序号
    activeTab: 0,
    // 四种状态的建议列表
    adviseList: [{
        total: 0,
        records: []
      },
      {
        total: 0,
        records: []
      },
      {
        total: 0,
        records: []
      },
      {
        total: 0,
        records: []
      }
    ],
    isShow: false,
    // 时间类型类表（-1：全部,0:一天内,1:三天内,2:七天内,3:一月内,4:半年内）
    timeList: [{
      timeType: -1,
      time: "全部"
    }, {
      timeType: 0,
      time: "一天内"
    }, {
      timeType: 1,
      time: "三天内"
    }, {
      timeType: 2,
      time: "七天内"
    }, {
      timeType: 3,
      time: "一月内"
    }, {
      timeType: 4,
      time: "半年内"
    }],
    // 时间条件
    time: '全部',
    // 时间类型（-1：全部,0:一天内,1:三天内,2:七天内,3:一月内,4:半年内）
    timeType: -1,
    // 地点关键字
    address: "",
    // 内容关键字
    key: ""
  },

  /**
   * 非页面的初始数据
   */
  userData: {
    phone: "",
    pageSize: 6
  },
// 长按出现删除按钮
showDeleteButton(e){
  if(this.data.deleindex != null){
    this.setData({
      deleindex: null
    })
  }else{
    this.setData({
      deleindex:e.currentTarget.dataset.id,
      showDelete: true // 长按时显示删除按钮
    });
  }
},
//  删除按钮点击 
Deleteid(e){
  wx.showModal({
    title: '提示',
    content: '确定删除吗',
    showCancel: true, // 是否显示取消按钮，默认为 true
    success(res) {
      if (res.confirm) {
        deleteAdvise(e.currentTarget.dataset.id).then(Response =>{
          if(Response.code === 200){
            wx.showToast({
              icon: "success",
              title: '删除成功',
            })
            wx.startPullDownRefresh();
          }
        })
      } else if (res.cancel) {
        this.setData({
          deleindex: null
        })
      }
    }
  })
},
  //空方法，去除警告，不可删除
  onInput() {
    // 空方法，去除警告，不可删除
  },

  // 呈现弹窗
  show() {
    this.setData({
      isShow: true
    })
  },

  // 退出弹窗
  quit() {
    this.setData({
      isShow: false
    })
  },

  // 获取时间类型
  getTimeType(e) {
    this.setData({
      time: this.data.timeList[e.detail.value].time,
      timeType: this.data.timeList[e.detail.value].timeType,
    })
  },

  // 重置筛选数据
  reset() {
    this.setData({
      time: '全部',
      timeType: -1,
      address: "",
      key: ""
    })
  },

  // 修改状态栏
  changeTabbar(e) {
    let status = e.currentTarget.dataset.status
    this.setData({
      activeTab: Number(status)
    })
  },
  // 导航栏回调函数
  onTabItemTap(item) {
    const SUBSCRIBE_ID = 'rCqojgVMHvET8c1pdftXuE--cQDD3AmM5hUkPk-QCGY' // 模板ID
    let that = this;
    if (wx.requestSubscribeMessage) {
      wx.requestSubscribeMessage({
        tmplIds: [SUBSCRIBE_ID],
        success(res) {
          if (res[SUBSCRIBE_ID] === 'accept') {
            // 用户主动点击同意...do something
          } else if (res[SUBSCRIBE_ID] === 'reject') {
            // 用户主动点击拒绝...do something
          } else {
            wx.showToast({
              title: '授权订阅消息有误',
              icon: 'none'
            })
          }
        },
        fail(res) {
          // 20004:用户关闭了主开关，无法进行订阅,引导开启
          if (res.errCode == 20004) {
            // 显示引导设置弹窗
            that.setData({
              isShowSetModel: true
            })
          }else{
            // 其他错误信息码，对应文档找出原因
            wx.showModal({
              title: '提示',
              content: res.errMsg,
              showCancel: false
            })
          }
        }
      });
    } else {
      wx.showModal({
        title: '提示',
        content: '请更新您微信版本，来获取订阅消息功能',
        showCancel: false
      })
    }
  },
  // 条件查询数据
  check() {
    this.setData({
      adviseList: [{
          total: 0,
          records: []
        },
        {
          total: 0,
          records: []
        },
        {
          total: 0,
          records: []
        },
        {
          total: 0,
          records: []
        }
      ],
    })
    let phone = this.userData.phone
    let firstAddress = this.data.firstAddress == "全部" ? "" : this.data.firstAddress
    this.getAdvisePage(phone, 0, firstAddress, this.data.secondAddress, 0, this.data.timeType, this.data.address, this.data.key)
    this.getAdvisePage(phone, 1, firstAddress, this.data.secondAddress, 1, this.data.timeType, this.data.address, this.data.key)
    this.getAdvisePage(phone, 2, firstAddress, this.data.secondAddress, 3, this.data.timeType, this.data.address, this.data.key)
    this.getAdvisePage(phone, 3, firstAddress, this.data.secondAddress, 4, this.data.timeType, this.data.address, this.data.key)
    this.quit()
  },

  // 跳转页面
  jumpPage(e) {
    let stateCode = e.currentTarget.dataset.state
    let id = e.currentTarget.dataset.id
    if (0 <= stateCode && stateCode <= 2) {
      console.log('222')
      wx.navigateTo({
        url: '/pages/handle/handle?id=' + id,
      })
    } else {
      console.log(id)
      wx.navigateTo({
        url: '/pages/releaseInfo/releaseInfo?id=' + id,
      })
    }

  },

  // 获取加页数据
  getAdviseList() {
    console.log(1);
    let activeTab = this.data.activeTab
    let phone = this.userData.phone
    // (phone,index, firstAddress, secondAddress, stateCode, timeType, address, key) 
    let firstAddress = this.data.firstAddress == "全部" ? "" : this.data.firstAddress
    if (activeTab < 2) {
      this.getAdvisePage(phone, activeTab, firstAddress, this.data.secondAddress, activeTab, this.data.timeType, this.data.address, this.data.key)
    } else {
      this.getAdvisePage(phone, activeTab, firstAddress, this.data.secondAddress, activeTab + 1, this.data.timeType, this.data.address, this.data.key)
    }
  },

  // 条件查找所有建议
  getAdvisePage(phone, index, firstAddress, secondAddress, stateCode, timeType, address, key) {
    let adviseList = this.data.adviseList
    let advise = adviseList[index]
    if (advise.records.length < advise.total || advise.total == 0) {
      let pageSize = this.userData.pageSize
      let page = Number(advise.records.length / pageSize) + 1
      
      getAdvisePage(phone, page, pageSize, firstAddress, secondAddress, stateCode, timeType, address, key).then(res => {
        
        advise.total = res.data.total
        advise.records = advise.records.concat(res.data.records)
        adviseList[index] = advise
        
        this.setData({
          adviseList: adviseList
        })
      })
    }
  },

  // 获取群众手机号
  getMyInfo() {
    let phone = wx.getStorageSync('phoneNumber')
    this.getAdvisePage(phone, 0, "", "", 0, -1, "", "")
    this.getAdvisePage(phone, 1, "", "", 1, -1, "", "")
    this.getAdvisePage(phone, 2, "", "", 3, -1, "", "")
    this.getAdvisePage(phone, 3, "", "", 4, -1, "", "")
    this.userData.phone = phone
  },

  // 获取二级管理员辖区列表
  getAdminAddress() {
    let addressList = wx.getStorageSync('addressList')
    let secondAddress = wx.getStorageSync('address')
    this.getAdvisePage("", 0, "", secondAddress, 0, -1, "", "")
    this.getAdvisePage("", 1, "", secondAddress, 1, -1, "", "")
    this.getAdvisePage("", 2, "", secondAddress, 3, -1, "", "")
    this.getAdvisePage("", 3, "", secondAddress, 4, -1, "", "")
    if (addressList.length > 1) {
      this.setData({
        addressList,
        secondAddress
      })
    } else {
      this.setData({
        secondAddress
      })
    }
  },

  //获取选择的管理员辖区
  updateAdminAddress(e) {
    
    this.setData({
      secondAddress: this.data.addressList[e.detail.value]
    })
    this.reset()
    this.check()
  },

  //获取选择的辖区
  getAddress(e) {
    
    let locationList = this.data.locationList
    let secondAddress = locationList[1][e.detail.value[1]].address
    this.setData({
      firstAddress: locationList[0][e.detail.value[0]].address,
      secondAddress: secondAddress == "全部" ? "" : secondAddress
    })
    this.reset()
    this.check()
  },

  //更新二级辖区列表
  updateSecondAddress(e) {
    if (e.detail.column == 0) {
      let id = this.data.locationList[0][e.detail.value].id
      this.getSecondAddress(id)
    }
  },

  //获取一级辖区列表
  getFirstAddress() {
    getFirstAddress().then(res => {
      res.data.unshift({
        id: 0,
        address: "全部"
      })
      
      this.setData({
        'locationList[0]': res.data,
        firstAddress: res.data[0].address
      })
    })
  },

  //获取二级辖区列表
  getSecondAddress(id) {
    getSecondAddress(id).then(res => {
      res.data.unshift({
        id: 0,
        address: "全部"
      })
      
      this.setData({
        'locationList[1]': res.data,
      });
    })
  },

  // 初始化页面数据
  getPageData() {
    wx.setNavigationBarTitle({
      title: '上报信息',
    })
    let code = wx.getStorageSync("code")
    if (code == getApp().globalData.firstCode) {
      this.getFirstAddress()
      this.getSecondAddress(0)
      // (phone,index, firstAddress, secondAddress, stateCode, timeType, address, key)
      this.getAdvisePage("", 0, "", "", 0, -1, "", "")
      this.getAdvisePage("", 1, "", "", 1, -1, "", "")
      this.getAdvisePage("", 2, "", "", 3, -1, "", "")
      this.getAdvisePage("", 3, "", "", 4, -1, "", "")
    } else if (code == getApp().globalData.secondCode) {
      this.getAdminAddress()
    } else {
      this.getMyInfo()
    }
    this.setData({
      code: code,
    })
  },
  // 获取定阅授权信息
  getsubscription(){
    wx.requestSubscribeMessage({
      tmplIds: ['nv1mxHUoxpWxfIZv4Z6oUh9PdP5MWnP5Vl39OCIiA8k'], // 此处可填写多个模板 ID，但低版本微信不兼容只能授权一个
      success (res) {
        console.log('已授权接收订阅消息')
      }
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.getPageData()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onshow() {},

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {
    this.reset()
    this.setData({
      adviseList: [{
          total: 0,
          records: []
        },
        {
          total: 0,
          records: []
        },
        {
          total: 0,
          records: []
        },
        {
          total: 0,
          records: []
        }
      ]
    })
    this.getPageData()
    return;
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },
})